import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Microscope, Search } from "lucide-react";
import { useState } from "react";
import { UnifiedCard } from "./UnifiedCard";

const stemProjects = [
  {
    id: "1",
    title: "Climate Data Analysis",
    description: "Analyze real climate datasets using Python and create predictive models",
    discipline: "Environmental Science",
    difficulty: "Intermediate",
    duration: "2-3 hours",
    rating: 4.9,
    tools: ["Python", "Pandas", "Matplotlib"],
    categories: ["Environmental Science", "Data Science"],
    popularity: 2456
  },
  {
    id: "2",
    title: "Arduino Smart Home System",
    description: "Build an IoT system to monitor temperature, humidity, and control devices",
    discipline: "Engineering & Robotics",
    difficulty: "Advanced",
    duration: "4-5 hours",
    rating: 4.8,
    tools: ["Arduino", "C++", "Sensors"],
    categories: ["Engineering & Robotics"],
    popularity: 1893
  },
  {
    id: "3",
    title: "DNA Extraction Lab",
    description: "Extract DNA from fruits using household items and observe under microscope",
    discipline: "Biology",
    difficulty: "Beginner",
    duration: "1-2 hours",
    rating: 4.7,
    tools: ["Lab Kit", "Microscope"],
    categories: ["Biology"],
    popularity: 3241
  },
  {
    id: "4",
    title: "Solar Panel Efficiency Test",
    description: "Design experiments to test solar panel efficiency under different conditions",
    discipline: "Physics",
    difficulty: "Intermediate",
    duration: "3-4 hours",
    rating: 4.6,
    tools: ["Multimeter", "Solar Panels"],
    categories: ["Physics", "Environmental Science"],
    popularity: 1567
  },
  {
    id: "5",
    title: "Mathematical Modeling",
    description: "Create mathematical models to solve real-world optimization problems",
    discipline: "Math & Data Science",
    difficulty: "Advanced",
    duration: "2-3 hours",
    rating: 4.5,
    tools: ["MATLAB", "Excel"],
    categories: ["Math & Data Science"],
    popularity: 934
  },
  {
    id: "6",
    title: "Basic Circuit Building",
    description: "Learn electronics fundamentals by building simple LED circuits",
    discipline: "Engineering & Robotics",
    difficulty: "Beginner",
    duration: "1-2 hours",
    rating: 4.8,
    tools: ["Breadboard", "LEDs", "Resistors"],
    categories: ["Engineering & Robotics"],
    popularity: 2789
  },
  {
    id: "7",
    title: "Python Data Visualization",
    description: "Create interactive charts and graphs from real datasets using Python",
    discipline: "Computer Science",
    difficulty: "Intermediate",
    duration: "2-3 hours",
    rating: 4.6,
    tools: ["Python", "Matplotlib", "Plotly"],
    categories: ["Computer Science", "Data Science"],
    popularity: 2156
  }
];

const filterCategories = [
  { id: "all", label: "All Projects" },
  { id: "environmental", label: "Environmental Science" },
  { id: "physics", label: "Physics" },
  { id: "biology", label: "Biology" },
  { id: "math", label: "Math & Data Science" },
  { id: "engineering", label: "Engineering & Robotics" },
  { id: "computer", label: "Computer Science" }
];

export function STEMDiscovery() {
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("popular");

  const filteredProjects = stemProjects.filter(project => {
    // Search filter
    const matchesSearch = searchQuery === "" || 
      project.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      project.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      project.tools.some(tool => tool.toLowerCase().includes(searchQuery.toLowerCase())) ||
      project.discipline.toLowerCase().includes(searchQuery.toLowerCase());

    // Category filter
    const matchesCategory = selectedCategory === "all" || 
      project.categories.some(category => {
        const categoryMap: { [key: string]: string } = {
          "environmental": "Environmental Science",
          "physics": "Physics",
          "biology": "Biology",
          "math": "Math & Data Science",
          "engineering": "Engineering & Robotics",
          "computer": "Computer Science"
        };
        return categoryMap[selectedCategory] === category;
      });

    return matchesSearch && matchesCategory;
  }).sort((a, b) => {
    switch (sortBy) {
      case "popular":
        return b.popularity - a.popularity;
      case "recent":
        return 0; // Would use actual dates in real implementation
      case "duration-short":
        return parseInt(a.duration) - parseInt(b.duration);
      case "duration-long":
        return parseInt(b.duration) - parseInt(a.duration);
      default:
        return 0;
    }
  });

  const handleCategoryFilter = (categoryId: string) => {
    setSelectedCategory(categoryId);
  };

  const handleStartProject = (projectTitle: string) => {
    console.log(`Starting project: ${projectTitle}`);
    // Mirror Agent integration would trigger here
  };

  return (
    <div className="space-y-6">
      {/* Subtitle */}
      <div className="text-center">
        <p className="text-gray-600 text-sm">
          Hands-on STEM projects with real-world applications and AI guidance
        </p>
      </div>

      {/* Sticky Filter Bar */}
      <div className="sticky top-0 bg-white z-10 pb-4 border-b border-gray-100">
        <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
          {/* Search */}
          <div className="relative w-full lg:w-80">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="Search STEM projects..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>

          {/* Sort */}
          <Select value={sortBy} onValueChange={setSortBy}>
            <SelectTrigger className="w-full lg:w-48">
              <SelectValue placeholder="Sort by" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="popular">Most Popular</SelectItem>
              <SelectItem value="recent">Recently Added</SelectItem>
              <SelectItem value="recommended">Recommended for Me</SelectItem>
              <SelectItem value="duration-short">Duration (Short–Long)</SelectItem>
              <SelectItem value="duration-long">Duration (Long–Short)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* Category Filter Pills */}
        <div className="flex items-center gap-2 flex-wrap mt-4">
          {filterCategories.map((category) => (
            <Button
              key={category.id}
              variant={selectedCategory === category.id ? "default" : "outline"}
              size="sm"
              onClick={() => handleCategoryFilter(category.id)}
              className={`${
                selectedCategory === category.id 
                  ? "bg-gray-900 text-white hover:bg-gray-800" 
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200 border-gray-300"
              } rounded-full px-4 py-2`}
            >
              {category.label}
            </Button>
          ))}
        </div>
      </div>

      {/* Statistics */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-600">
          Found {filteredProjects.length} projects
        </p>
        <Badge variant="secondary" className="bg-blue-100 text-blue-700">
          Total Students: {stemProjects.reduce((sum, project) => sum + project.popularity, 0)}
        </Badge>
      </div>
      
      {/* Projects Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredProjects.map((project) => (
          <UnifiedCard
            key={project.id}
            title={project.title}
            description={project.description}
            subjectLabel={project.discipline}
            difficultyLevel={project.difficulty}
            topicTags={project.tools}
            duration={project.duration}
            subject={project.discipline}
            userCount={project.popularity}
            rating={project.rating}
            onPreview={() => console.log(`Preview project: ${project.title}`)}
            onPrimaryAction={() => handleStartProject(project.title)}
            primaryActionLabel="Start Project"
            previewLabel="Preview"
            isHot={project.popularity > 2500}
            isPriority={project.rating >= 4.8}
          />
        ))}
      </div>

      {/* No Results */}
      {filteredProjects.length === 0 && (
        <div className="text-center py-12">
          <Microscope className="w-12 h-12 mx-auto mb-4 text-gray-400" />
          <p className="text-gray-600 mb-2">No projects found</p>
          <p className="text-sm text-gray-500">Try adjusting your search or filters</p>
          <Button 
            variant="outline" 
            onClick={() => {
              setSearchQuery("");
              setSelectedCategory("all");
              setSortBy("popular");
            }}
            className="mt-4"
          >
            Clear Filters
          </Button>
        </div>
      )}
    </div>
  );
}
